package com.lin.utils;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import javax.xml.bind.DatatypeConverter;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Random;
import java.util.TreeMap;
import java.util.UUID;

/**
 * Copyright(C),2022年-2022,霖霖
 *
 * @author 霖霖
 * @version 1.0
 * @date 2023/5/1 13:32
 * @Description
 */
public class TTSAuth {
    public static String sign(String s, String key, String method) throws Exception {
        Mac mac = Mac.getInstance(method);
        SecretKeySpec secretKeySpec = new SecretKeySpec(key.getBytes(StandardCharsets.UTF_8), mac.getAlgorithm());
        mac.init(secretKeySpec);
        byte[] hash = mac.doFinal(s.getBytes(StandardCharsets.UTF_8));
        return DatatypeConverter.printBase64Binary(hash);
    }

    public static String getStringToSign(String method, String endpoint, TreeMap<String, Object> params) {
        StringBuilder s2s = new StringBuilder();
        s2s.append(method).append(endpoint).append("/?");

        for (String k : params.keySet()) {
            s2s.append(k).append("=").append(params.get(k).toString()).append("&");
        }
        return s2s.substring(0, s2s.length() - 1);
    }

    public static String getUrl(TreeMap<String, Object> params) throws UnsupportedEncodingException {
        StringBuilder url = new StringBuilder("https://tts.tencentcloudapi.com/?");
        // 实际请求的url中对参数顺序没有要求
        for (String k : params.keySet()) {
            // 需要对请求串进行urlencode，由于key都是英文字母，故此处仅对其value进行urlencode
            url.append(k).append("=").append(URLEncoder.encode(params.get(k).toString(), "UTF-8")).append("&");
        }
        return url.substring(0, url.length() - 1);
    }

    public static void main(String[] args) throws Exception {

        TreeMap<String, Object> params = new TreeMap<>();
        params.put("Nonce", new Random().nextInt(java.lang.Integer.MAX_VALUE));
        // use current timestamp by default, in seconds
        params.put("Timestamp", System.currentTimeMillis() / 1000);
        params.put("Region", "ap-chengdu");
        params.put("SecretId", "AKIDvgCTVIrBG6hmcDZfW8VcWCdojPp0wd4G");
        params.put("Action", "TextToVoice");
        params.put("Version", "2019-08-23");
        params.put("SessionId", UUID.randomUUID());
        params.put("Text", "哟西哟西");
        params.put("Language", "zh-CN");
        String str2sign = getStringToSign("GET", "tts.tencentcloudapi.com", params);
        String signature = sign(str2sign, "znNioeHgqkPoytZ0B7pHUSAcpnVyB9sN", "HmacSHA1");
        System.out.println("Signature=" + signature);
        params.put("Signature", signature);
        System.out.println(getUrl(params));
    }

    public static String init(String text) throws Exception {
        TreeMap<String, Object> params = new TreeMap<>();
        params.put("Nonce", new Random().nextInt(java.lang.Integer.MAX_VALUE));
        // use current timestamp by default, in seconds
        params.put("Timestamp", System.currentTimeMillis() / 1000);
        params.put("Region", "ap-chengdu");
        params.put("SecretId", "AKIDvgCTVIrBG6hmcDZfW8VcWCdojPp0wd4G");
        params.put("Action", "TextToVoice");
        params.put("Version", "2019-08-23");
        params.put("SessionId", UUID.randomUUID());
        params.put("Text", text);
        params.put("Language", "zh-CN");
        String str2sign = getStringToSign("GET", "tts.tencentcloudapi.com", params);
        String signature = sign(str2sign, "znNioeHgqkPoytZ0B7pHUSAcpnVyB9sN", "HmacSHA1");
        System.out.println("Signature=" + signature);
        params.put("Signature", signature);
        String url = getUrl(params);
        System.out.println(url);
        return url;
    }
}
